package exercise;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @classname:MD5Demo
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/10 23:13
 * @version: 0.1
 * @since:1.8
 */
public class MD5Util {
    private MD5Util() {
    }
    //设置字符集
    private static final String ENCODEONG = "UTF-8";
    //增加盐值 salt 普通字符串 增加破译的难度
    private static final String SALT="*&^%FIGHTEN*&6";

    public static String encodeStr(String sourceStr) {
        Objects.requireNonNull(sourceStr);
        //创建信息摘要对象
        MessageDigest messageDigest = null;
        try {
            //创建实例设置算法格式
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //在加密之前增加盐值到字符串
        sourceStr = sourceStr+SALT;
        //将加密的字符串提交到messageDigest
        messageDigest.update(sourceStr.getBytes(Charset.forName(ENCODEONG)));
        //执行加密
        byte[] digest = messageDigest.digest();
        //将字节数组转换BigInteger（参数 -1转换成负数 0转换成0，1转换成正数）
        BigInteger bigInteger = new BigInteger(1,digest);
        //转换成16进制
        String string = bigInteger.toString(16);
        //将结果全部转换成大写
        String result = string.toUpperCase();
        return result;
    }

    public static void main(String[] args) {
        String pass = "1234";
        System.out.println(encodeStr(pass));
    }
}
